/*
 * @Author: your name
 * @Date: 2022-01-05 10:28:51
 * @LastEditTime: 2022-01-05 11:11:02
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: /socket/server.cpp
 */
#include <stdio.h>  // printf
#include <string.h> // memset
#include <stdlib.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h> //socket
#include <netinet/in.h>// IPPROTO_TCP, sockaddr_in

int main()
{
    // socket ctor
    int serv_sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); //TCP/IP family, connection-based byte streams,  Exterior Gateway Protocol

    // bind IP and port with socket
    struct sockaddr_in serv_addr;
    memset(&serv_addr,0,sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
    serv_addr.sin_port = htons(1234);
    bind(serv_sock,(struct sockaddr*)&serv_addr, sizeof(serv_addr));

    // listen status
    listen(serv_sock, 20);

    // accept request from cilent
    struct sockaddr_in clnt_addr;
    socklen_t clnt_addr_size = sizeof(clnt_addr);
    int clnt_sock = accept(serv_sock,(struct sockaddr*)(&clnt_addr), &clnt_addr_size);

    //send data 2 cilent
    char str[] = "hello,world";
   write(clnt_sock,str,sizeof(str));

    //close socket
    close(serv_sock);
    close(clnt_sock);


    return 0;
}